const effectConfig = require('../configs/effectConfig');
module.exports = class {
    constructor() {
        this.effectPrefab = null;
        //
        this.effectMap = {};
        this.effectPool = new cc.NodePool();
        this.effectCurLevel = 0;
        //
        this.init();
    }

    init() {
        //
        this.effectLayer = cc.find('Canvas/layerGame/gameLayerEffect');
    }

    loadEffectRes() {
        ICPC.addOneLoad();
        cc.loader.loadRes(effectConfig.effectPrefabPath, cc.Prefab, (error, resource) => {
            if (error) {
                throw error;
            }
            if (!(resource instanceof cc.Prefab)) {
                console.error('#25 Prefab error', effectConfig.effectPrefabPath);
                return;
            }
            this.effectPrefab = resource;
            ICPC.emit('loadEffectResEnd');
            ICPC.oneLoadOver();
        });
    }

    //私用
    newEffect() {
        if (this.effectPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            return this.effectPool.get();
        } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
            return cc.instantiate(this.effectPrefab);
        }
    }

    //私用
    deleteEffect(effectNode) {
        this.effectPool.put(effectNode);
    }

    getEffectCurConfig() {
    }

    startEffect() {
        const conf = this.getEffectCurConfig();
        let info = Object.assign(conf);
        //
        info.xv = Math.random() * conf.xv;
        if (Math.random() > 0.5) {
            info.xv *= -1;
        }
        this.addEffect(info);
    }

    getEffect(id) {
        return this.effectMap[id];
    }

    showMessage(message, pos = cc.v2(0, 0)) {
        this.addEffect({effectName: 'message1', effectInfo: message}, pos);
    }

    addEffect(effectFlag, pos) {
        //
        const id = ICPC.randId();
        let effectNode = this.newEffect();
        this.effectMap[id] = {
            m_node: effectNode,
            m_info: effectFlag,
            //effectName
            //effectInfo
        };
        this.effectLayer.addChild(effectNode);
        effectNode.setPosition(pos);
        effectNode.getComponent('effect').initEffect(id, effectFlag.effectName, effectFlag.effectInfo);
        //通知外部
        ICPC.emit('addEffect', id);
    }

    killEffect(id) {
        let effect = this.effectMap[id];
        if (effect) {
            this.deleteEffect(effect.m_node);
            delete this.effectMap[id];
        } else {
            console.error('特效无效');
        }
    }
}